<template>
  <div class="container" style="background:rgb(241, 241, 241);">
    <div class="left-board" style="background:white;">
      <!-- <div class="logo-wrapper">
        <div class="logo">移动端设计</div>
      </div> -->
      <el-scrollbar class="left-scrollbar">
        <!-- 左边：表单项 -->
        <div class="components-list">
          <template>
            <el-tabs v-model="tabName" @tab-click="tabClick" :stretch="true">
              <el-tab-pane label="页面目录" name="first">
                <leftPageMenu :pageOptions="pageList" @activePage="activePage"></leftPageMenu>
              </el-tab-pane>
              <el-tab-pane label="组件目录" name="second">
                <div v-for="(item, listIndex) in leftComponents" :key="listIndex">
                  <div class="components-title" style="display:flex;align-items:center;">
                    <!-- <svg-icon icon-class="component" /> -->
                    <img v-if="item.title.trim()" :src="item.iconTitle" alt="" style="width:25px;height:25px;margin-right:5px;">
                    {{ item.title }}
                  </div>
                  <draggable
                    class="components-draggable-mobile"
                    :list="item.list"
                    :group="{ name: 'componentsGroup', pull: 'clone', put: false }"
                    
                    draggable=".components-item-m"
                    :sort="false"
                    @end="onEnd"
                  >
                    <div
                      v-for="(element, index) in item.list"
                      :key="index"
                      class="components-item-m"
                      @click="addComponent(element)"
                      :draggable="true"
                      @dragstart="dragInfo(element)"
                    >
                      <div class="components-item-mobile">
                          <div class="components-body-mobile">
                            <img :src="editIcon[element.__config__.tag]" alt="">
                        </div>
                      </div>
                      <div class="lable">{{ element.__config__.label }}</div>
                    </div>
                  </draggable>
                </div>
              </el-tab-pane>
            </el-tabs>
          </template>
         

          <!-- 左边：动态表单 -->
          <!-- <el-form ref="form" :model="form" :rules="rules" label-width="55px" :disabled="isEdit">
            <el-form-item label="表单名" prop="tableName">
              <el-input v-model="form.tableName" placeholder="请输入表单名" />
            </el-form-item>
            <el-form-item label="开启状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio v-for="dict in this.getDictDatas(DICT_TYPE.COMMON_STATUS)"
                          :key="dict.value" :label="parseInt(dict.value)">{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="备注" prop="tableRemark">
              <el-input type="textarea" v-model="form.tableRemark" placeholder="请输入备注" />
            </el-form-item>
          </el-form> -->
        </div>
      </el-scrollbar>
    </div>

    <div class="center-board1" style="margin-top:20px;">
      <div class="action-bar" style="border:none;">
        <!-- <el-button icon="el-icon-check" type="text" @click="save">保存</el-button> -->
               <!-- <el-button icon="el-icon-video-play" type="text" @click="run">
         运行
       </el-button> -->
       
       <el-button type="primary" plain size="mini" icon="el-icon-view" @click="preview">预览</el-button>
        <!-- <el-button icon="el-icon-view" type="text" @click="showJson">
          查看json
        </el-button> -->
<!--        <el-button icon="el-icon-download" type="text" @click="download">-->
<!--          导出vue文件-->
<!--        </el-button>-->
<!--        <el-button class="copy-btn-main" icon="el-icon-document-copy" type="text" @click="copy">-->
<!--          复制代码-->
<!--        </el-button>-->
        
        <el-button type="danger" plain size="mini" icon="el-icon-delete" @click="empty">清空</el-button>
      </div>

      <!-- 中间，表单项 -->
      <el-scrollbar class="center-scrollbar" style="background-color: #f1f1f1">
         <div class="miniApp" style="left: 50%">
            <div class="editor">
              <div class="editor-caption">
                <!-- <div class="arrow"></div> -->
                <div class="editor-title-wrapper">{{curPageName}}</div>
                <div class="nav-rightbtn-group">
                  <img :src="rightBtn" alt="">
                </div>
              </div>
              <div class="appContent1" @dragover="dragBtnOver($event)">
                <grid-layout
                  :layout.sync="drawingList"
                  :col-num="12"
                  :row-height="30"
                  :is-draggable="true"
                  :is-resizable="true"
                  :is-mirrored="false"
                  :vertical-compact="true"
                  :margin="[0, 5]"
                  :use-css-transforms="true"
                  :style="{marginBottom:navList.length>0?'68px':'0px'}"
                >
                  <grid-item v-for="(item,index) in drawingList"
                    :x="item.x"
                    :y="item.y"
                    :w="item.w"
                    :h="item.h"
                    :i="item.i"
                    :key="item.i"
                    @resized="resizedEvent"
                    @moved="movedEvent"
                  >
                    <draggable-item
                      :key="index"
                      :drawing-list="drawingList"
                      :current-item="item"
                      :index="index"
                      :active-id="activeId"
                      @activeItem="activeFormItem"
                      @copyItem="drawingItemCopy"
                      @deleteItem="drawingItemDelete"
                      @handDrop="handDrop"
                      @freemoved="movedEventFree"
                      @freeresize="resizedEventFree"
                      style="width:100%;height:100%;border:1px solid blue;overflow: auto"
                    />
                  </grid-item>  
                </grid-layout>
                <draggable-item
                  v-if="navList.length>0"
                
                 
                  :current-item="navList[0]"
              :index="0"
                  :drawing-list="navList"
                  @activeItem="activeFormItem"
                  @deleteItem="navItemDelete"
                  style="position:absolute;bottom:0;border:1px solid blue;width:100%;height:68px;overflow: hidden;"
                />
                <div v-show="!drawingList.length" class="empty-info">
                  从左侧点选组件进行移动端设计
                </div>
              </div>
            </div>
          </div>
      </el-scrollbar>
    </div>

    <!-- 右边：组件属性/表单属性 -->
    <right-panel
      :active-data="activeData"
      :show-field="!!drawingList.length || !!navList.length"
    />

   <!-- <form-drawer
     :visible.sync="drawerVisible"
     :form-data="formData"
     size="100%"
     :generate-conf="generateConf"
   /> -->

    <json-drawer
      size="60%"
      :visible.sync="jsonDrawerVisible"
      :json-str="JSON.stringify(formData)"
      @refresh="refreshJson"
    />

   <!-- <code-type-dialog
     :visible.sync="dialogVisible"
     title="选择生成类型"
     :show-file-name="showFileName"
     @confirm="generate"
   /> -->

 <!-- <el-dialog title="表单预览" :visible.sync="dialogPreviewVisible" :fullscreen="fullScreen" @close="dialogClose">
    <span slot="title" class="el-dialog__title">
      表单预览
      <i class="el-icon-full-screen" v-if="!fullScreen" @click="()=>{fullScreen = true}" style="float:right;marginRight:25px;"></i>
      <i class="el-icon-aim" v-else @click="()=>{fullScreen = false}" style="float:right;marginRight:25px;"></i>
    </span>
    <div style="display:flex;justifyContent:center;">
    <parser :form-conf="formConfData" status="add" :originData="{}" v-if="dialogPreviewVisible"
        @cancel="dialogClose" @insert="insert" @updateTableData='updateTableData' @del='del'
        @copyData="copyData" @moveUp='moveUp' @edit='changeEditColumn' @moveDown='moveDown' :style="{width:fullScreen?'80%':'100%'}"
        @click='drawerClick' :showHideData='showHideData' :key="time" @reset="reset" @curPageChange="curPageChange"/>
    </div>
 </el-dialog> -->
 <!-- <div v-if="showSubDialog"><SubFormEditDialog :curRowNum="curRowNum" :curRowCompData="curRowCompData" :config="curRowCompConfig"
  :tableIndex="tableIndex" @updateTableData='updateTableData' @confirm="subFormConfirm" @cancel="showSubDialog = false"></SubFormEditDialog></div> -->
<!--    <input id="copyNode" type="hidden">-->
     <!-- <el-drawer :visible.sync="drawer" direction="rtl" :before-close='closeDrawer'>
      <span slot="title" style="fontSize:20px;">列显隐</span>
      <el-table :data="showHideData" size="small" border style="width:80%;marginLeft:10%;">
        <el-table-column prop="columnName" label="列名" align="center">
        </el-table-column>
        <el-table-column prop="hide" label="隐藏" align="center">
          <template slot-scope="scope">
            <el-checkbox v-model="scope.row.hide"></el-checkbox>
          </template>
        </el-table-column>
      </el-table>
    </el-drawer> -->
    <el-dialog :modal-append-to-body="false" title="移动端预览" :visible.sync="dialogPreviewVisible" :fullscreen="fullScreen" @close="dialogPreviewVisible=false">
    <span slot="title" class="el-dialog__title">
      移动端预览
    </span>
    <div style="display:flex;justifyContent:center;">
     <mobile-draw :pageListAll="{pageList,navList}" status="view" v-if="dialogPreviewVisible"></mobile-draw> 
    </div>
 </el-dialog>
  </div>
</template>

<script>
import rightBtn from '@/assets/images/rightBtn.png'
import draggable from 'vuedraggable'
import { debounce } from 'throttle-debounce'
import { saveAs } from 'file-saver'
import ClipboardJS from 'clipboard'
import render from '@/components/render/render'
import FormDrawer from '@/views/infra/build/FormDrawer'
import JsonDrawer from '@/views/infra/build/JsonDrawer'
import RightPanel from './RightPanel'
import parser from './parser'
import SubFormEditDialog from './SubFormEditDialog.vue'
import leftPageMenu from './leftPageMenu'
import { basicComponents,advancedComponents,chartComponents,pageOptions } from './mobileConfig'
import {
  exportDefault, beautifierConf, isNumberStr, titleCase, deepClone, isObjectObject
} from '@/utils/index'
import {
  makeUpHtml, vueTemplate, vueScript, cssStyle
} from '@/components/generator/html'
import { makeUpJs } from '@/components/generator/js'
import { makeUpCss } from '@/components/generator/css'
import logo from '@/assets/logo/logo.png'
import CodeTypeDialog from '@/views/infra/build/CodeTypeDialog'
import DraggableItem from './DraggableItem'
import {
  getDrawingList, saveDrawingList, getIdGlobal, saveIdGlobal, getFormConf
} from '@/utils/db'
import loadBeautifier from '@/utils/loadBeautifier'
import {CommonStatusEnum} from "@/utils/constants";
import {createForm, getForm, updateForm} from "@/api/bpm/form";
import {decodeFields} from "@/utils/formGenerator";
import VueGridLayout from 'vue-grid-layout';
import mobileDraw from './mobileDraw.vue'
let beautifier
const emptyActiveData = { style: {}, autosize: {} }
let oldActiveId
let tempActiveData
// const drawingListInDB = getDrawingList()
// const formConfInDB = getFormConf()
// const idGlobal = getIdGlobal()
let editIcon = {
  'vantField':require('@/assets/images/wenzi.png'),
  'vantImagee':require('@/assets/images/vanImage.png'),
  'vantSwipe':require('@/assets/images/vanSwipe.png'),
  'vantButton':require('@/assets/images/button.png'),
  'word-swipe':require('@/assets/images/wordlunbo.png'),
  'imgandtext':require('@/assets/images/tuwen.png'),
  'mobileSearch':require('@/assets/images/ic_sousuo.png'),
  'message-List':require('@/assets/images/xiaoxi.png'),
  'source-detail':require('@/assets/images/datadetail.png'),
  'biaoqian':require('@/assets/images/ic_biaoqian.png'),
  'information-item':require('@/assets/images/xinxilist.png'),
  'vantGrid':require('@/assets/images/dibudaohang.png'),
  'myTask':require('@/assets/images/woderenwu.png'),
  'functionMenu':require('@/assets/images/gongnengcaidan.png')
}
export default {
  components: {
    draggable,
    render,
    FormDrawer,
    JsonDrawer,
    RightPanel,
    CodeTypeDialog,
    DraggableItem,
    parser,
    SubFormEditDialog,
    leftPageMenu,
    GridLayout: VueGridLayout.GridLayout,
    GridItem: VueGridLayout.GridItem,
    mobileDraw
  },
  props: ['isEdit','idDefault'],
  data() {
    return {
      tabName:'first',
      editIcon:editIcon,
      logo,
      labelWidth: 100,
      drawingData: {}, // 生成后的表单数据
      activeId: '',
      drawer:false,
      drawingList: [], // 表单项的数组
      navList: [], //底部导航栏
      dialogPreviewVisible: false,
      drawerVisible: false,
      formData: {},
      dialogVisible: false,
      jsonDrawerVisible: false,
      generateConf: null,
      showFileName: false,
      activeData: basicComponents[0], // 右边编辑器激活的表单项
      leftComponents: [
        {
          title: '基础组件',
          list: basicComponents,
          iconTitle:require('@/assets/images/mobilejichu.png')
        },
        {
          title: '高级组件',
          list: advancedComponents,
          iconTitle:require('@/assets/images/mobilegaoji.png')
        },
        {
          title: ' ',
          list: chartComponents
        }
      ],
      formConfData: {},
    
     
      fullScreen: false,
      showHideData:[],
      curRowCompData: [],
      curRowCompConfig: {},
      curRowNum: -1,
      tableIndex: '',
      showSubDialog: false, // 子表单编辑时 弹窗模式
      pageList:[],
      rightBtn,
      curPageName:'',
      curDrag:{},
      biaoqianDrawList:[]
    }
  },
  computed: {
  },
  watch: {
   dialogPreviewVisible(val){
    this.$store.commit('mobile/SET_JUMP',val);
   }
  },
  mounted() {
  
  },
  created() {
     this.pageList = deepClone(pageOptions);
      this.drawingList = this.pageList[0].children[0].fields;
      this.curPageName = this.pageList[0].children[0].name;
  },
  methods: {
    dragInfo(obj){
      this.curDrag = obj;
    },
    handDrop(obj){
      if(this.curDrag.__config__.tag==='biaoqian'){
        this.$message.warning('布局容器不支持布局容器组件');
        return;
      }
      if(this.curDrag.__config__.tag==='vantGrid'){
        this.$message.warning('布局容器不支持底部导航组件');
        return;
      }
      let info = this.createIdAndKey(this.curDrag,obj.fields);
      obj.tabList[obj.curtab].fields.push(info);
      obj.showtip = false;
      this.biaoqianDrawList.push(info);
    },
    dragBtnOver(e){
      e.preventDefault()
    },
    activePage(fields,name){
      this.drawingList = fields;
      this.curPageName = name;
      console.log(fields,'fsafds');
      this.activeFormItem(this.drawingList[0]);
    },
    movedEvent(i, newX, newY){
      let layvalue = this.drawingList.find(item=>{
        return item.i === i;
      });
      layvalue.x=newX
      layvalue.y=newY
    },
    resizedEvent(i, newH, newW, newHPx, newWPx){
      let layvalue = this.drawingList.find(item=>{
        return item.i === i;
      });
        layvalue.w=newW
      layvalue.h=newH
      layvalue.moveHeight = newHPx;
      layvalue.moveWidth = newWPx;
      this.$forceUpdate()
    },
    movedEventFree(i, newX, newY){
      let layvalue = this.biaoqianDrawList.find(item=>{
        return item.i === i;
      });
      layvalue.x=newX
      layvalue.y=newY
    },
    resizedEventFree(i, newH, newW, newHPx, newWPx){
      let layvalue = this.biaoqianDrawList.find(item=>{
        return item.i === i;
      });
        layvalue.w=newW
      layvalue.h=newH
      layvalue.moveHeight = newHPx;
      layvalue.moveWidth = newWPx;
      this.$forceUpdate()
    },
    tabClick(tab, event) {
    },
    activeFormItem(currentItem) {
      // console.log(currentItem,65656565);
      this.activeData = currentItem || basicComponents[0];
    },
    onEnd(obj) {
      
    },
    addComponent(item) {
     
      
     
     let clone = this.createIdAndKey(item);
    
      if (clone.__config__.tag === 'vantGrid') {
        if(!this.navList.length){
          this.navList.push(clone)  
          
        }else{
          this.$message.warning('一个小程序只允许出现一个底部导航栏');
        }
  
      }else{ 
        this.drawingList.push(clone);
        
      }
      this.activeFormItem(clone)
    },
   
    createIdAndKey(item,arr) {
      let y = arr ? arr.length : this.drawingList.length;
      let nowid = Date.now();
      let clonea = deepClone(item);
      if (clonea.__config__.layout === 'colFormItem') {
        clonea.__vModel__ = `field${nowid}`
      }
      clonea.__config__.renderKey = nowid;
      if(clonea.__config__.tag !== 'vantGrid'){
          clonea.i = nowid;
      clonea.y = y;
      clonea.x = 0;
      clonea.w = item.w || 12;
      clonea.h =item.gridh ? Math.ceil(item.gridh/74.6) : 1;
      }
      if(clonea.__config__.tag==='biaoqian'){
        let arr = clonea.tabList;
        arr.forEach((info1,index)=>{
         info1.fields.forEach((info2,ind)=>{
          info2.__vModel__ = `field${nowid}${index}${ind}`;
          info2.i = `${nowid}${index}${ind}`;
          info2.__config__.renderKey = `${nowid}${index}${ind}`;
         })
        })
      }
      return clonea;
    },
    // 获得表单数据
    AssembleFormData() {
      this.formData = {
        fields: deepClone(this.drawingList)
      }
    },
    empty() {
      this.$confirm('确定要清空所有组件吗？', '提示', { type: 'warning' }).then(
        () => {
          this.drawingList = []
          this.navList = []
           function emptyDraw(arr){
            arr.forEach(item=>{
              if(item.fields){
                item.fields = [];
              }
              if(Array.isArray(item.children)){
                emptyDraw(item.children);
              }
            })
          }
          this.pageList.forEach(val=>{
            if(Array.isArray(val.children)){
              emptyDraw(val.children);
            }
            
          })
          this.pageList.forEach(val=>{
            if(Array.isArray(val.children)){
              val.children.forEach(c=>{
                if(c.name===this.curPageName){
                  this.drawingList = c.fields;
                }
              });
            }
            
          })
        }
      )
    },
    drawingItemCopy(item, list) {
    let clone = this.createIdAndKey(item,list);
      list.push(clone)
      this.activeFormItem(clone)
    },
    drawingItemDelete(index, list) {
      list.splice(index, 1)
      this.$nextTick(() => {
        const len = list.length
        if (len) {
          this.activeFormItem(list[len - 1])
        }
      })
    },
    navItemDelete() {
      this.navList = [];
    },
   
    showJson() {
      this.AssembleFormData()
      this.jsonDrawerVisible = true
    },
    download() {
      this.dialogVisible = true
      this.showFileName = true
      this.operationType = 'download'
    },
    run() {
      this.dialogVisible = true
      this.showFileName = false
      this.operationType = 'run'
    },
    copy() {
      this.dialogVisible = true
      this.showFileName = false
      this.operationType = 'copy'
    },
   
    refreshJson(data) {
      console.log(data,'refreshjson');
      this.drawingList = deepClone(data.fields)
      console.log(this.drawingList,'this.drawingListrefresh');
      delete data.fields
    
    },
    preview(){
     this.dialogPreviewVisible = true;
    }
  }
}
</script>
<style lang="scss" scoped>
.el-button--danger.is-plain{
  border:none;
}
.el-button--primary.is-plain{
  border:none;
}
</style>
<style lang='scss'>
@import '@/styles/loginFrom';
@import '@/styles/home';
.van-grid-item__content {
  padding: 8px;
}
.editor-title-wrapper{
    text-align: center;
    width: 100%;
}
</style>
